import { Toast } from "antd-mobile"
import { reqlogin } from "../../http/api"

// state 
const initState = {
    user: {
        phone: "",
        password: ""
    },
    info: sessionStorage.getItem("isLogin")?JSON.parse(sessionStorage.getItem("isLogin")):{}
}

// action type
const TYPES = {
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    LOGIN_USER_INFO: "LOGIN_USER_INFO"
}

// reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        case TYPES.LOGIN_USER_INFO:
            return {
                ...state,
                info:action.info
            }
        default:
            return state
    }
}

// action creator
export const actions = {
    changeUser: (key, value) => ({ type: TYPES.LOGIN_CHANGE_USER, key, value }),
    changeInfo:info=>{
        if(info.token){
            sessionStorage.setItem("isLogin",JSON.stringify(info))
        }else{
            sessionStorage.removeItem("isLogin")
        }
        return {type:TYPES.LOGIN_USER_INFO,info}
    },
    doLogin: (push) => {
        return (dispatch, getState) => {
            let user = getUser(getState())
            reqlogin(user).then(res => {
                if (res.data.code === 200) {
                    Toast.show({
                        content: res.data.msg
                    })
                    dispatch(actions.changeInfo(res.data.list))
                    push("/index/home")
                }
            })
        }
    }
}

// selector导出数据给组件
export const getUser = state => state.login.user

export const getInfo = state => state.login.info

// 导出reducer
export default reducer